//com.tanhua.server.service.IMService
package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.client.naming.net.NamingProxy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.HuanXinApi;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UsersApi;
import com.tanhua.dubbo.pojo.*;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class IMService {

    @DubboReference(version = "1.0.0")
    private HuanXinApi huanXinApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    @DubboReference(version = "1.0.0")
    private UsersApi usersApi;
    @DubboReference(version = "1.0.0")
    private QuanZiApi quanZiApi;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private AnnouncementService announcementService;

    public UserInfoVo queryUserInfoByUserName(String userName) {
        HuanXinUser huanXinUser = this.huanXinApi.queryUserByUserName(userName);
        if (null == huanXinUser) {
            return null;
        }
        UserInfo userInfo = this.userInfoApi.queryByUserId(huanXinUser.getUserId());
        UserInfoVo userInfoVo = BeanUtil.toBeanIgnoreError(userInfo, UserInfoVo.class);

        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);
        return userInfoVo;
    }

    /**
     * 添加好友
     *
     * @param friendId 好友id
     */
    public boolean contactUser(Long friendId) {
        Long userId = UserThreadLocal.get();

        //添加好友关系到环信
        Boolean result = this.huanXinApi.addUserFriend(userId, friendId);

        //添加好友关系到MongoDB
        if (result) {
            return this.usersApi.saveUsers(userId, friendId) != null;
        }
        return false;
    }

    public PageResult queryContactsList(Integer page, Integer pageSize, String keyword) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        Long userId = UserThreadLocal.get();

        List<UserInfo> friendIdUserInfoList;
        if (StrUtil.isEmpty(keyword)) {
            //查询列表
            PageInfo<Users> pageInfo = this.usersApi.queryUsersList(userId, page, pageSize);
            //查询用户信息列表
            List<Object> friendIdList = CollUtil.getFieldValues(pageInfo.getRecords(), "friendId");
            friendIdUserInfoList = this.userInfoApi.queryByUserIdList(friendIdList);
        } else {
            //搜索
            List<Users> usersList = this.usersApi.queryAllUsersList(userId);
            List<Object> friendIdList = CollUtil.getFieldValues(usersList, "friendId");
            friendIdUserInfoList = this.userInfoApi.queryLikeNickName(keyword, friendIdList);
        }

        List<UsersVo> usersVoList = new ArrayList<>();
        for (UserInfo userInfo : friendIdUserInfoList) {
            UsersVo usersVo = BeanUtil.toBeanIgnoreError(userInfo, UsersVo.class);
            usersVo.setUserId("HX_" + userInfo.getUserId());//环信id
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setCity(StrUtil.subBefore(userInfo.getCity(), "-", false));
            usersVoList.add(usersVo);
        }

        pageResult.setItems(usersVoList);
        return pageResult;
    }

    /**
     * 点赞
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryMessageLikeList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLikeCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);
    }

    /**
     * 喜欢
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryLoveCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);
    }

    /**
     * 评论
     *
     * @param page
     * @param pageSize
     * @return
     */
    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        Long userId = UserThreadLocal.get();
        PageInfo<Comment> pageInfo = this.quanZiApi.queryCommentListByUser(userId, page, pageSize);
        return this.fillUserCommentList(pageInfo);
    }

    private PageResult fillUserCommentList(PageInfo<Comment> pageInfo) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(pageInfo.getPageNum());
        pageResult.setPagesize(pageInfo.getPageSize());
        List<Comment> records = pageInfo.getRecords();
        if (CollUtil.isEmpty(records)) {
            return pageResult;
        }
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        List<UserInfo> userInfoList = this.userInfoService.queryUserInfoByUserIdList(userIdList);
        ArrayList<MessageCommentVo> messageCommentVoList = new ArrayList<>();
        for (Comment comment : records) {
            for (UserInfo userInfo : userInfoList) {
                if (ObjectUtil.equal(comment.getUserId(), userInfo.getUserId())) {
                    MessageCommentVo messageCommentVo = new MessageCommentVo();
                    messageCommentVo.setId(comment.getId().toHexString());
                    messageCommentVo.setAvatar(userInfo.getLogo());
                    messageCommentVo.setNickname(userInfo.getNickName());
                    messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));
                    messageCommentVoList.add(messageCommentVo);
                    break;
                }
            }
        }
        pageResult.setItems(messageCommentVoList);
        return pageResult;
    }

    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {
        IPage<Announcement> announcementPage = this.announcementService.queryList(page, pageSize);
        ArrayList<AnnouncementVo> announcementVoList = new ArrayList<>();
        for (Announcement record : announcementPage.getRecords()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));
            announcementVoList.add(announcementVo);
        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(announcementVoList);
        return pageResult;

    }
}

